package cn.gzmli.dtt.common.entity;

import cn.gzmli.dtt.common.entity.PageInfo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Descript
 * @Author xsx
 * @Date 2017/12/25
 */
public class Result implements Serializable {
    private static final long serialVersionUID = -1146882923993895926L;
    private Integer status;
    private String msg;
    private Object data;
    private PageInfo pageInfo;

    public Result() {
    }

    public Result(Integer status, String msg) {
        this(status, msg, null);
    }

    public Result(Integer status, String msg, Object data) {
        this(status, msg, data, null);
    }

    public Result(Integer status, String msg, Object data, PageInfo pageInfo) {
        this.status = status;
        this.msg = msg;
        this.data = data;
        this.pageInfo = pageInfo;
    }

    public Result(Integer status, BindingResult bindingResult) {
        if (bindingResult != null && bindingResult.hasErrors()) {
            this.status =status;
            this.msg = "数据不完整";
            this.data = getValidData(bindingResult);
        }
    }

    private Map getValidData(BindingResult result) {
        Map<String, Object> map = new HashMap<>();
        for (FieldError fieldError : result.getFieldErrors()) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return map;
    }


    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public PageInfo getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(PageInfo pageInfo) {
        this.pageInfo = pageInfo;
    }

    @Override
    public String toString() {
        return "Result{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
